//
//  AppDelegate.m
//  VoiceMusic
//
//  Created by dllo on 15/10/15.
//  Copyright © 2015年 zhangdeyu. All rights reserved.
//

#import "AppDelegate.h"
#import "ViewController.h"
#import <RESideMenu.h>
#import "ZCMainViewController.h"
#import "ZCSetUpViewController.h"
#import <Masonry.h>
#import "ZCPlayMusicViewController.h"
#import <UIImageView+WebCache.h>
#import "ZCSingleTool.h"
#import "ZCPlayMusicTool.h"
#import "ZCMainModel.h"
#import <UMSocial.h>
@interface AppDelegate ()<RESideMenuDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) RESideMenu *menu;
@property (nonatomic, strong) UIView *playView;
@property (nonatomic, assign) BOOL isplay;
//@property (nonatomic, strong) ZCPlayMusicViewController *playVC;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *headButton;
@property (nonatomic, strong) NSMutableArray *listArr;

//列表的点击控制
@property (nonatomic, assign) BOOL isList;
@end

@implementation AppDelegate
- (void)dealloc
{
    _tableView.delegate = nil;
    _tableView.dataSource = nil;
    _menu.delegate = nil;
}
////只执行一次
//-(ZCPlayMusicViewController *)playVC{
//
//    if(!_playVC){
//        _playVC = [[ZCPlayMusicViewController alloc] init];
//    }
//    return _playVC;
//}

//隐藏抽屉
-(void)hide:(NSNotification *)not{
    [self.menu hideMenuViewController];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    // 友盟分享的账号
    [UMSocialData setAppKey:@"507fcab25270157b37000010"];
        
    //抽屉跳转
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hide:) name:@"Hidden" object:nil];
    
    //每次来设置都可以直接播放
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isLocal"];
    self.listArr = [NSMutableArray array];
    NSArray *sendBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [[sendBox lastObject] stringByAppendingPathComponent:@"list.plist"];
    self.listArr = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    // Override point for customization after application launch.
    
    ZCSetUpViewController *side = [[ZCSetUpViewController alloc] init];
    ZCMainViewController *main = [[ZCMainViewController alloc] init];
    UINavigationController *mainVc = [[UINavigationController alloc] initWithRootViewController:main];
    self.menu = [[RESideMenu alloc] initWithContentViewController:mainVc leftMenuViewController:nil rightMenuViewController:side];
    self.window.rootViewController = self.menu;
    //设置抽屉样式
    self.menu.menuPreferredStatusBarStyle = 3;
    self.menu.delegate= self ;
    self.menu.contentViewShadowColor = [UIColor colorWithRed:0.870 green:0.312 blue:0.069 alpha:0.000];
    self.menu.contentViewShadowOffset = CGSizeMake(300, 0);
    self.menu.contentViewShadowOpacity = 0.6;
    self.menu.contentViewShadowRadius = 12;
    self.menu.contentViewShadowEnabled = YES;
    
    self.playView = [[UIView alloc] init];
    self.playView.backgroundColor = [UIColor colorWithRed:1.000 green:0.682 blue:0.242 alpha:1.000];
    [self.menu.view addSubview:self.playView];
    self.playView.tag = 9999;

    //创建播放控件
    [self.playView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.equalTo(self.menu.view);
        make.height.equalTo(@49);
    }];
    [self creatPlay];
    self.playView.userInteractionEnabled =YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ta:)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [self.playView addGestureRecognizer:tap];
   
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(play:) name:@"play" object:nil];
    //监听播放列表
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(list:) name:@"arr" object:nil];
    //监听播放完毕playList
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(end:) name:@"end" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Ico:) name:@"playList" object:nil];
    
    
    //监听播放界面的状态
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chang:) name:@"chang" object:nil];
    
    
    return YES;
}


-(void)end:(NSNotification *)not{
    UIImageView *image = (UIImageView *)[self.window.rootViewController.view viewWithTag:10000];
    image.image = [UIImage imageNamed:@"iconfont-bofang"];
    self.isplay = NO;
     [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isLocal"];
}

-(void)list:(NSNotification *)not{
    
    self.listArr = not.userInfo[@"arr"];
    
    //将播放列表的数据归档
    NSArray *sendBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [[sendBox lastObject] stringByAppendingPathComponent:@"list.plist"];
    [NSKeyedArchiver archiveRootObject:self.listArr toFile:path];
   
    [self.tableView reloadData];
}
//赋值通知中心传值
-(void)play:(NSNotification *)not{
    
    UILabel *name = (UILabel *)[self.playView viewWithTag:10002];
    name.text = not.userInfo[@"name"];
    UILabel *nameSinge = (UILabel *)[self.playView viewWithTag:10003];
    nameSinge.text = not.userInfo[@"nameSinge"];
    UIImageView *heat = (UIImageView *)[self.playView viewWithTag:10004];
    [heat sd_setImageWithURL:[NSURL URLWithString:not.userInfo[@"heat"]] placeholderImage:[UIImage imageNamed:@"3187"]];
    
    UIImageView *image = (UIImageView *)[self.window.rootViewController.view viewWithTag:10000];
    image.image = [UIImage imageNamed:@"iconfont-zanting"];
    
    //保持永远点击完在点击下面的播放按钮都是暂停状态
    self.isplay = YES;
    //保存本地
    [[NSUserDefaults standardUserDefaults] setObject:not.userInfo[@"name"] forKey:@"name"];
    [[NSUserDefaults standardUserDefaults] setObject:not.userInfo[@"nameSinge"] forKey:@"nameSinge"];
    [[NSUserDefaults standardUserDefaults] setObject:not.userInfo[@"heat"] forKey:@"image"];
    
    [[NSUserDefaults standardUserDefaults] setObject:not.userInfo[@"url"] forKey:@"url"];
    
    //判断刚启动的时候,是否直接按播放按钮
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isLocal"];
    
}

//弹出播放界面
-(void)ta:(UITapGestureRecognizer *)ta{
    
    //单例方法
    [[ZCSingleTool shareSingTool].playVC show];

}

//创建播放视图
-(void)creatPlay{
    
    UIImageView *icoImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iconfont-bofangliebiao"]];
    icoImage.userInteractionEnabled = YES;
    icoImage.tag = 10001;
    [self.playView addSubview:icoImage];
    [icoImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.playView).offset(15);
        make.bottom.equalTo(self.playView).offset(-10);
        make.right.equalTo(self.playView).offset(-10);
        make.width.equalTo(@23);
    }];
    UITapGestureRecognizer *tapIco = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(Ico:)];
    tapIco.numberOfTapsRequired = 1;
    tapIco.numberOfTouchesRequired = 1;
    [icoImage addGestureRecognizer:tapIco];
    
    UIImageView *playImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iconfont-bofang"]];
    playImage.userInteractionEnabled = YES;
    playImage.tag = 10000;
    [self.playView addSubview:playImage];
    [playImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.playView).offset(15);
        make.bottom.equalTo(self.playView).offset(-10);
        make.right.equalTo(icoImage.mas_left).offset(-30);
        make.width.equalTo(@23);
    }];
    UITapGestureRecognizer *tapPlay = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(playy:)];
    tapPlay.numberOfTapsRequired = 1;
    tapPlay.numberOfTouchesRequired = 1;
    [playImage addGestureRecognizer:tapPlay];
  
    
    UILabel *name = [[UILabel alloc] init];
    name.userInteractionEnabled = YES;
    name.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"name"];
    name.tag = 10002;
    [self.playView addSubview:name];
    [name mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.playView).offset(2);
        make.left.equalTo(self.playView.mas_left).offset(80);
        make.width.equalTo(@200);
        make.height.equalTo(@25);
    }];
    
    UILabel *nameSing = [[UILabel alloc] init];
    nameSing.userInteractionEnabled = YES;
    nameSing.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"nameSinge"];
    nameSing.tag = 10003;
    nameSing.font = [UIFont systemFontOfSize:15];
    [self.playView addSubview:nameSing];
    
    [nameSing mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.playView).offset(-2);
        make.left.equalTo(self.playView.mas_left).offset(80);
        make.width.equalTo(@200);
        make.height.equalTo(@20);
    }];
    
    UIImageView *heat = [[UIImageView alloc] init];
    //heat.backgroundColor = [UIColor greenColor];
    heat.userInteractionEnabled = YES;
    heat.layer.cornerRadius = 25;
    heat.layer.masksToBounds = YES;
    heat.tag = 10004;
    
    //获取头像图片
    [heat sd_setImageWithURL:[NSURL URLWithString:[[NSUserDefaults standardUserDefaults] objectForKey:@"image"]] placeholderImage:[UIImage imageNamed:@"3187"]];
    
    [self.playView addSubview:heat];
    [heat mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.playView).offset(0);
        make.bottom.equalTo(self.playView).offset(0);
        make.left.equalTo(self.playView).offset(10);
        make.width.equalTo(@50);
    }];
    
    [self creatList];
    
}

-(void)creatList{
    
    self.headButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.headButton.backgroundColor = [UIColor colorWithWhite:0.808 alpha:1.000];
    self.headButton.frame = CGRectMake(0, 0, WIDTH, HEIGHT - 50);
    self.headButton.hidden = YES;
    self.headButton.alpha = 0.5;
    [self.window.rootViewController.view addSubview:self.headButton];
    [self.headButton addTarget:self action:@selector(retu:) forControlEvents:UIControlEventTouchUpInside];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.rowHeight = 70;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.bounces = NO;
    self.tableView.backgroundColor = [UIColor colorWithRed:0.802 green:1.000 blue:0.398 alpha:1.000];
    self.tableView.alpha = 0.9;
    self.tableView.hidden = YES;
    [self.window.rootViewController.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.window.rootViewController.view);
        make.bottom.equalTo(self.window.rootViewController.view).offset(-50);
        make.height.equalTo(@230);
    }];
    
   
}
-(void)retu:(UIButton *)bu{
    self.tableView.hidden = YES;
    self.headButton.hidden = YES;
}


//歌曲列表的点击方法
- (void)Ico:(UITapGestureRecognizer *)not{
    if(self.isList){
        [self.tableView bringSubviewToFront:self.window.rootViewController.view];
        self.tableView.hidden = NO;
        self.headButton.hidden = NO;
    }else{
        self.tableView.hidden = YES;
        self.headButton.hidden = YES;
    }
    self.isList = ! self.isList;
}
-(NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.listArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *re = @"re";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:re];
    if(!cell){
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:re];
    }
    if(self.listArr.count != 0){
        
        ZCMainModel *model = self.listArr [indexPath.row];
        cell.textLabel.text = model.name;
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        cell.textLabel.numberOfLines = 0;
        cell.detailTextLabel.text = model.singerName;
    }

    return cell;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return @"播放列表";
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ZCMainModel *model = self.listArr[indexPath.row];
    
    if(model.auditionList.count == 0) {
        UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"消息" message:@"歌曲版权不支持" preferredStyle:UIAlertControllerStyleAlert];
        [self.window.rootViewController presentViewController:alter animated:YES completion:nil];
        [self.window.rootViewController dismissViewControllerAnimated:YES completion:^{
        }];
        return;
    }

    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:model.name,@"name",model.singerName,@"nameSinge",model.picUrl,@"heat",model.auditionList[0][@"url"],@"url",nil];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"play" object:self userInfo:dic];
    //把歌曲存到本地
    [[NSUserDefaults standardUserDefaults] setObject:model.auditionList[0][@"url"] forKey:@"url"];
    [ZCPlayMusicTool sharePlay].urlMusic = model.auditionList[0][@"url"];
    [ZCPlayMusicTool getPlay:model.auditionList[0][@"url"]];
    
}


//播放点击方法
- (void)playy:(UITapGestureRecognizer *)pl{
    
    //点击暂停和播放
    if(!self.isplay){
        
        UIImageView *image = (UIImageView *)[self.window.rootViewController.view viewWithTag:10000];
        image.image = [UIImage imageNamed:@"iconfont-zanting"];
        
        if([[NSUserDefaults standardUserDefaults] boolForKey:@"isLocal"]){
            //播放音乐
            [ZCPlayMusicTool getPlay:[[NSUserDefaults standardUserDefaults] objectForKey:@"url"]];
            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isLocal"];
        }else{
            [[ZCPlayMusicTool sharePlay].player play];
        }
    
        [ZCPlayMusicTool sharePlay].isplay = YES;
        
    }else{

        UIImageView *image = (UIImageView *)[self.window.rootViewController.view viewWithTag:10000];
        image.image = [UIImage imageNamed:@"iconfont-bofang"];
        [[ZCPlayMusicTool sharePlay].player pause];
        [ZCPlayMusicTool sharePlay].isplay = NO;
    }
    
    self.isplay =! self.isplay;
}

//改变图标
-(void)chang:(NSNotification *)not{
    
    if([ZCPlayMusicTool sharePlay].isplay){
        UIImageView *image = (UIImageView *)[self.window.rootViewController.view viewWithTag:10000];
        image.image = [UIImage imageNamed:@"iconfont-zanting"];
        
    }else{
        UIImageView *image = (UIImageView *)[self.window.rootViewController.view viewWithTag:10000];
        image.image = [UIImage imageNamed:@"iconfont-bofang"];
    }
    
}







- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
